package com.exampl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exampl.common.CustomException;
import com.exampl.dao.OrdersDao;
import com.exampl.domain.*;
import com.exampl.dto.OrdersDto;
import com.exampl.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    HttpSession session;

    @Autowired
    ShoppingService shoppingService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional
    @CacheEvict(value = "setmealCache", allEntries = true)  // 全局清除套餐缓存
    public void submit(Orders orders) {
        // 全局清除菜品缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        // 获取到用户id
        Long user_id = (Long) session.getAttribute("user");
        // 获取用户
        User user = userService.getById(user_id);
        // 获取购物车中的商品
        LambdaQueryWrapper<ShoppingCart> lqw1 = new LambdaQueryWrapper<ShoppingCart>();
        lqw1.eq(ShoppingCart::getUserId, user_id);
        List<ShoppingCart> carts = shoppingService.list(lqw1);
        if(carts == null){
            // 购物车为空
            throw new CustomException("购物车为空，无法下单！");
        }
        AtomicInteger amount = new AtomicInteger(0);
        // 使用类获取订单id
        long order_id = IdWorker.getId();
        // 将购物车的商品存储到订单明细中
        for(ShoppingCart cart:carts){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order_id);
            orderDetail.setImage(cart.getImage());
            orderDetail.setName(cart.getName());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            amount.addAndGet(cart.getAmount().multiply(new BigDecimal(cart.getNumber())).intValue());
            orderDetailService.save(orderDetail);
            // 提交完成之后改变菜品或套餐的月售
            // 修改菜品月售
            if(cart.getDishId() != null){
                Long dishId = cart.getDishId();
                Dish dish = dishService.getById(dishId);
                dish.setSaleNum(dish.getSaleNum() + cart.getNumber());
                dishService.updateById(dish);
            }else {
                // 修改套餐月售
                Long setmealId = cart.getSetmealId();
                Setmeal setmeal = setmealService.getById(setmealId);
                setmeal.setSaleNum(setmeal.getSaleNum() + cart.getNumber());
                setmealService.updateById(setmeal);
            }
        }
        // 获取地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        // 添加到订单表
        orders.setUserId(user_id);
        orders.setId(order_id);
        orders.setNumber(String.valueOf(order_id));
        orders.setStatus(2);
        orders.setCheckoutTime(new Date());
        orders.setOrderTime(new Date());
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        this.save(orders);
        // 清空购物车
        shoppingService.remove(lqw1);
    }

    @Override
    public Page<OrdersDto> getPage(Integer page, Integer pageSize) {
        // 获取当前用户id
        Object user_id = session.getAttribute("user");
        Page<Orders> page1 = new Page<Orders>(page, pageSize);
        Page<OrdersDto> page2 = new Page<OrdersDto>();
        LambdaQueryWrapper<Orders> orderslqw = new LambdaQueryWrapper<Orders>();
        orderslqw.eq(Orders::getUserId, user_id);
        orderslqw.orderByDesc(Orders::getOrderTime);
        this.page(page1, orderslqw);
        // 赋值数据给Dto
        BeanUtils.copyProperties(page1, page2, "records");
        // 设置Dto的数据
        List<Orders> orders = page1.getRecords();
        List<OrdersDto> ordersDtoList = orders.stream().map((data) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(data, ordersDto);
            Long id = data.getId();
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<OrderDetail>();
            lqw.eq(OrderDetail::getOrderId, id);
            List<OrderDetail> orderDetails = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        page2.setRecords(ordersDtoList);
        return page2;
    }
}
